package com.spk.test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Assert;
import org.junit.Test;

/**
 * 认证测试类 此类只需要增加一个CustomRealm类
 * Created by Wangminze on 2017/3/25.
 * Description:
 */
public class AuthenticatorTest02 {

    @Test
    public void testLoginAndLogout(){

        //构建我们的SecurityManager工厂，通过外部配置文件，init文件构建出来
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:config/shiro_realm.ini");

        //拿到工厂安全管理器
        SecurityManager securityManager = factory.getInstance();

        //设置到运行环境当中，使用单例
        SecurityUtils.setSecurityManager(securityManager);

        //拿到主体：我们的请求端
        Subject subject = SecurityUtils.getSubject();

        //UsernamePasswordToken是Authentication的实现类，带有客户的登录信息
        AuthenticationToken token = new UsernamePasswordToken("zhangsan","123123");

        //执行认证提交
        try {
            subject.login(token);
        }catch (AuthenticationException e){
            e.printStackTrace();
        }

        //对主体认证状态进行判断
        boolean isAuthenticated = subject.isAuthenticated();
        System.out.println("是否认证通过——" + isAuthenticated);

        Assert.assertTrue(isAuthenticated);

    }

}
